<template>
  <div>
    <!-- 顶部输入框区域 -->
    <div class="header">
      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <el-row type="flex" justify="space-between">
          <el-form label-width="70px" :inline="true">

            <el-col :span="15">
              <el-col>
                <el-form-item :label="proxy.$t('table.name')">
                  <el-input v-model="queryData.name" :placeholder="proxy.$t('table.Enter')" clearable></el-input>
                </el-form-item>
              </el-col>

              <el-col>
                <el-form-item :label="proxy.$t('table.community')">
                  <el-select v-model="queryData.community_code" @change="changeValue"
                    :placeholder="proxy.$t('table.Enter')" clearable filterable>
                    <el-option v-for="item in allCommunityList" :key="item.id" :value="item.code" :label="item.name">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col>
                <el-form-item :label="proxy.$t('table.building')">
                  <el-select v-model="queryData.building_code" :placeholder="proxy.$t('table.Enter')" clearable
                    filterable>
                    <el-option v-for="item in buildingList" :key="item.id" :value="item.code" :label="item.name">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col>
                <el-form-item :label="proxy.$t('table.aptTime')">
                  <el-date-picker v-model="queryData.adopt_time" type="datetimerange"
                    :start-placeholder="proxy.$t('table.start')" :end-placeholder="proxy.$t('table.end')" clearable />
                </el-form-item>
              </el-col>
            </el-col>

            <el-col :span="6">
              <el-col>
                <el-form-item>
                  <el-button type="primary" @click="onSearch">{{ proxy.$t('table.search') }}</el-button>
                  <el-button @click="resetForm">{{ proxy.$t('table.reset') }}</el-button>
                </el-form-item>
              </el-col>
            </el-col>
          </el-form>
        </el-row>

      </el-card>
    </div>

    <!-- 表格内容区域 -->
    <div class="content">

      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <!-- 按钮区域 -->
        <el-row justify="end">
          <div>
            <el-button type="info" @click="exportToExcel">导出信息</el-button>
            <el-button type="primary" @click="addRef.isShow = true">{{ proxy.$t('table.add') }}</el-button>
            <RefreshRight style="width: 1em; height: 1em; margin-right: 8px; margin-left: 8px;" />
            <Operation style="width: 1em; height: 1em; margin-right: 8px" />
            <Tools style="width: 1em; height: 1em; margin-right: 8px" />
          </div>
          <div></div>
        </el-row>
        <br>

        <!-- 表格区域 -->
        <el-table :data="list" stripe>
          <el-table-column :label="proxy.$t('table.name')" prop="name">
          </el-table-column>
          <el-table-column :label="proxy.$t('table.color')" prop="color">
          </el-table-column>
          <el-table-column :label="proxy.$t('table.picture')" prop="photo">
            <template #default="{ row }">
              <ImagePreview :src="row.photo" :width="100" :height="100" />
            </template>
          </el-table-column>
          <el-table-column :label="proxy.$t('table.community')" prop="community_code">
            <template #default="{ row }">
              {{ row.community?.name }}
            </template>
          </el-table-column>
          <el-table-column :label="proxy.$t('table.building')" prop="building_code" width="70">
            <template #default="{ row }">
              {{ row.building?.name }}
            </template>
          </el-table-column>
          <el-table-column :label="proxy.$t('table.Name')" prop="member_id">
            <template #default="{ row }">
              {{ row.member?.name }}
            </template>
          </el-table-column>
          <el-table-column :label="proxy.$t('table.tel')" prop="member_id">
            <template #default="{ row }">
              {{ row.member?.tel }}
            </template>
          </el-table-column>
          <el-table-column :label="proxy.$t('table.describe')" prop="">
            -
          </el-table-column>
          <el-table-column :label="proxy.$t('table.aptTime')" width="200" prop="adopt_time">
            <template #default="{ row }">
              {{ formatDate(row.adopt_time) }}
              <!-- {{ dayjs(row.adopt_time).format('YYYY-MM-DD HH:mm:ss') }} -->
            </template>
          </el-table-column>
          <el-table-column :label="proxy.$t('table.operate')" width="150">
            <template #default="{ row }">
              <el-button type="text" @click="editRow(row.id)">编辑</el-button>
              <el-button type="text" @click="delRow(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <br>

        <!-- 分页区域 -->
        <el-pagination @size-change="sizeChange" @current-change="currentChange" v-model:current-page="queryData.current"
          :page-sizes="[2, 5, 8, 10]" v-model:page-size="queryData.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </el-card>

      <!-- 抽屉区域 -->
      <addForm ref="addRef" @updateList="initData" />

    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, getCurrentInstance } from 'vue'
import { getPetListApi, delPetInfoApi, addPetInfoApi, editPetInfoApi } from '@/api/pet.js'
import addForm from './component/addForm'
import { getBuildingApi } from '@/api/community.js'
import { useAllCommunityList, useBuildingList, useHouseList } from '@/hooks/index.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '@/utils/index.js'
import * as XLSX from 'xlsx'
import { activeTable } from '@/hooks/activity.js'

// ===========================================

const { proxy } = getCurrentInstance()
const list = ref([])
const total = ref(0)
const addRef = ref()
const buildingList = ref([])
// const dayjs = require('dayjs')
const allCommunityList = useAllCommunityList()

// ===========================================

// 请求参数
const defaultData = () => ({
  current: 1,
  pageSize: 2,
  adopt_time: [],
  name: "",
  community_code: "",
  building_code: ""
})

const queryData = reactive(defaultData())

// 表格数据


// 搜索内容
const onSearch = () => {
  queryData.current = 1
  queryData.value.adopt_time = +new Date(queryData.value.adopt_time)
  initData()
}

// 重置表单
const resetForm = () => {
  Object.assign(queryData, {
    current: 1,
    pageSize: 2,
    adopt_time: "",
    name: "",
    community_code: "",
    building_code: ""
  })

  initData()
}

const initData = async () => {
  let res = await getPetListApi(queryData)
  console.log(res);

  // 赋值数据
  list.value = res.data.rows
  total.value = res.data.count
}

// 每页数量切换事件
const sizeChange = (val) => {
  // console.log('每页是', val);
  queryData.pageSize = val
  initData()
}

// 页码切换事件
const currentChange = (val) => {
  // console.log('页码是', val);
  queryData.current = val
  initData()
}


// 下拉框change事件
const changeValue = async (val) => {
  queryData.building_code = null
  let res = await getBuildingApi(val)
  // console.log(res);
  buildingList.value = res.data
}


// 删除事件
const delRow = async (id) => {
  try {
    // 删除确认框
    await ElMessageBox.confirm(
      '确定删除么?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      })

    // 发起网络请求
    await delPetInfoApi(id)

    // 边缘处理
    if (queryData.pageSize === 1 && list.value.length === 1) queryData.current--

    // 更新列表
    initData()
  } catch (error) {
    console.log(error);
  }
}

// 修改事件
const editRow = (id) => {
  addRef.value.replyData(id)
}


// 导出excel表格
const exportToExcel = () => {
  const key = Object.keys(list.value[0])
  const header = activeTable.map(item => item.label)// 表头信息
  const data = [header, ...list.value.map(item => [item.id, item.name, item.color, item.photo, item.community_code, item.building_code, item.member_id, item.member.tel, formatDate(item.adopt_time)])]
  const ws = XLSX.utils.aoa_to_sheet(data)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
  XLSX.writeFile(wb, 'tableData.xlsx')
}



onMounted(() => {
  initData()
})


</script>

<style scoped>
.header {
  margin: 40px;
}

.content {
  margin: 40px;
}
</style>